package br.fatec.servico;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import br.fatec.dominio.empresa.Empresa;
import br.fatec.dominio.empresa.INMantemEmpresaImpl;

public class MySQLConvenioDAO implements IConvenioDAO{
	private static final String cadastraConvenio = "INSERT INTO convenio (cnpj, dataInicio, dataFim) VALUES (?, ?, ?) ";
	private static final String consulta = "SELECT * FROM convenio WHERE cnpj LIKE ? ";
	private static final String altera = "UPDATE convenio SET dataInicio = ?,  dataFim = ? WHERE cnpj = ? ";
	private static final String exclui = "DELETE FROM convenio WHERE cnpj = ? ";
	String msg = "";

	@Override
	public int cadastra(String cnpj, Date dataInicio, Date dataFim) {
		PreparedStatement stmt;
		int rc = 0;
		try {				
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(cadastraConvenio);
			stmt.setString(1, cnpj);
			stmt.setDate(2, new java.sql.Date(dataInicio.getTime()));
			if (dataFim !=  null){
				stmt.setDate(3, new java.sql.Date(dataFim.getTime()));
			}else{
				stmt.setDate(3,(java.sql.Date) dataFim);
			}
			rc = stmt.executeUpdate();
			//stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
			System.out.println("metodo cadastra MysqlConvenioDao =" + e.getMessage());
		}
		return rc;
	}

	@Override
	public ResultSet consulta(String cnpj) {
		ResultSet rs = null;
		PreparedStatement stmt;
		try {
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(consulta);
			stmt.setString(1, cnpj);
			rs = stmt.executeQuery();			
			// stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
		}
		return rs;
	}

	@Override
	public int altera(String cnpj, Date dataInicio, Date dataFim) {
		PreparedStatement stmt;
		int rc = 0;
		try {
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(altera);
			if (dataInicio !=  null){
				stmt.setDate(1, new java.sql.Date(dataInicio.getTime()));			
				if (dataFim !=  null){
					stmt.setDate(2, new java.sql.Date(dataFim.getTime()));
				}else{
					stmt.setDate(2,(java.sql.Date) dataFim);
				}
				stmt.setString(3, cnpj);
				rc = stmt.executeUpdate();			
				stmt.close();
			}else{
				rc = 100;
			}
		} catch (SQLException e) {
			msg = e.getMessage();	
			
		}
		return rc;
	}


	@Override
	public int exclui(String cnpj) {
		PreparedStatement stmt;
		int rc = 0;
		try {
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(exclui);
			stmt.setString(1, cnpj);
			rc = stmt.executeUpdate();
			stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
		}
		return rc;
	}

	@Override
	public String getMessage() {
		// TODO Auto-generated method stub
		return msg;
	}

}
